﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Principal;
using Universum.Infrastructure.Persistence;
using Universum.Infrastructure.Persistence.Queries;
using Universum.Model.Domain;

namespace Universum.Model.Services
{
	public class FriendlyUrlServiceImpl : IFriendlyUrlService
	{
		IPrincipal _Principal;
		IRepository _Repository;
		public FriendlyUrlServiceImpl(
			IPrincipal principal,
			IRepository repository
			)
		{
			_Principal = principal;
			_Repository = repository;
		}

		static Regex accepted_characters_pattern =
			new Regex("[^a-zA-Z_0-9]", RegexOptions.Compiled);
		static Regex duplicate_dashes_pattern = 
			
			new Regex("(-)+", RegexOptions.Compiled);
		public string CreateSlugFrom(string @string)
		{
			if (@string.IsNullOrEmpty().IsFalse())
			{
				string result = accepted_characters_pattern.Replace(@string, "-");
				result = duplicate_dashes_pattern.Replace(result, "-");
				result = result.TrimFront('-').TrimBack('-');
				//int count = _Repository.Query(new ArticleByUsernameAndSlug(
				//    _Principal.Identity.Name,
				//    result)).Count();
				//if ( count > 0)
				//{
				//    result += '-' + count;
				//}
				//int count = _Repository.Query<Article>().Count();
				//result = count + "_" + result;
				return result;
			}
			return @string;
		}

		
	}
}
